package val.to.UI;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import val.to.Globals;
import val.to.R;
import val.to.Utility;
import val.to.ValtoServices;
import val.to.entities.DisplayMode;
import val.to.entities.Event;
import android.R.string;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

public class EventDetailsActivity extends MapActivity{
	
	private static final String MAP_URL = "http://gmaps-samples.googlecode.com/svn/trunk/articles-android-webmap/simple-android-map.html";
	private Event mEvent;
	private MapController mc;
	
	private MenuButton mMenuButton;
	private TextView mEventFriendsList;
	private boolean mCreateNewIntent;
	private SimpleDateFormat m_formatter = new SimpleDateFormat("HH:mm");

	
	@Override
    public void onCreate(Bundle savedInstanceState) 
	{		
		super.onCreate(savedInstanceState);
        setContentView(R.layout.event_details);
        
        Bundle bundle = getIntent().getExtras();
        mEvent = bundle.getParcelable("val.to.entities.Event");
        String src = bundle.getString("source");
        mCreateNewIntent = false;
        if (src != null && src.equals(EventsActivity.class.getName()))
        	mCreateNewIntent = true;  
        
        InitUIComponents();
	}
	
	private void InitUIComponents()
	{		
		TextView eventName = (TextView) findViewById(R.id.eventName);
		TextView eventDesc = (TextView) findViewById(R.id.eventDescription);
		TextView eventStartDate = (TextView) findViewById(R.id.eventStartDate);
		TextView eventEndDate = (TextView) findViewById(R.id.eventEndDate);
		mEventFriendsList = (TextView) findViewById(R.id.checkedInLabel);
		
		String dayDiffStart = Utility.getDayDiffFromNowAsString(mEvent.getStartDate());
		String timeTextStart =  m_formatter.format(mEvent.getStartDate());
		String dayDiffEnd = Utility.getDayDiffFromNowAsString(mEvent.getEndTime());
		String timeTextEnd =  m_formatter.format(mEvent.getEndTime());
		
		dayDiffStart = dayDiffStart == null ? "at " : dayDiffStart + " at ";
		dayDiffEnd = dayDiffEnd == null ? "at " : dayDiffEnd + " at ";

		
		eventName.setText(mEvent.getName());
		eventDesc.setText(mEvent.getDescription());
		eventStartDate.setText(dayDiffStart + timeTextStart);
		eventEndDate.setText(dayDiffEnd + timeTextEnd);
		
		mMenuButton = (MenuButton) findViewById(R.id.menuButton);
		mMenuButton.init(this);
		
		SetupMapView();
		
		TextView eventNewsFeedButton = (TextView) findViewById(R.id.eventAlbumNewsFeed);
		eventNewsFeedButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
            	ValtoServices.selectEvent(mEvent);
            	goToNewsFeed(DisplayMode.NewsFeed);
				finish();
			}
		});
		
		TextView eventAlbumButton = (TextView) findViewById(R.id.eventAlbumLink);
		eventAlbumButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
            	ValtoServices.selectEvent(mEvent);
            	goToNewsFeed(DisplayMode.Album);
				finish();
			}
		});
	}
	
	private void goToNewsFeed(DisplayMode displayMode)
	{		
		ValtoServices.SetDisplayMode(mEvent, displayMode);
		
		if(mCreateNewIntent)
		{
			Intent intent = new Intent(EventDetailsActivity.this, NewsFeed.class);
			startActivity(intent);
		}
	}
	
	@Override
    public void onResume() {
        super.onResume();
        
        mEventFriendsList.setText("Getting information about your friends...");
        
        if (Globals.FacebookSession.isSessionValid())
        {
        	new FriendsCheckinInfoTask().execute();
        }
    }
	
	private String GetFriendsListText(ArrayList<String> friendsList){
			
		final int explicitNames = 2;
		int counter = 0;
		boolean userCheckedIn = ValtoServices.isCheckedIntoEvent(mEvent.getId());
		
		StringBuilder str = new StringBuilder();
		if (userCheckedIn){
			str.append("You");
		}
		
		if (!userCheckedIn && friendsList.size() == 0){
			return "No friends are checked in";
		}
		
		for(int i = 0 ; i <= explicitNames && i < friendsList.size(); i++){
			if (i > 0 || userCheckedIn){
				str.append(i == friendsList.size() -1 ?  " and " : ", ");	
			}
			
			str.append(friendsList.get(i));
			counter++;
		}
		
		int theRest = friendsList.size() - counter;
		if (theRest > 0){
			str.append(String.format(" and %d other friends", theRest));
		}
		
		String beVerb = (userCheckedIn || friendsList.size() > 1) ? " are " : " is ";		
		str.append(beVerb);
		str.append("checked in");
		return str.toString();
	}
	
	private void SetupMapView()
	{
		MapView mapView = (MapView) findViewById(R.id.eventMap);
	    mapView.setBuiltInZoomControls(true);
	    
	    mc = mapView.getController();
        mc.setZoom(13);
        
        mapView.showContextMenu();
        
        Drawable drawable = this.getResources().getDrawable(R.drawable.bulbgrey4);        
        SelectedLocationOverlay itemOverlay = new SelectedLocationOverlay(drawable, this,false);
        
        GeoPoint p = new GeoPoint((int)(mEvent.getLatitude()*1E6), (int)(mEvent.getLongitude()*1E6));
    	OverlayItem item = new OverlayItem(p, mEvent.getName(), mEvent.getDescription());
    	itemOverlay.addOverlay(item);
    	mc.animateTo(p);
        
        mapView.getOverlays().add(itemOverlay);
        mapView.invalidate();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
    private class FriendsCheckinInfoTask extends AsyncTask<Void, Void, Void> {
    	
    	private ArrayList<String> mItems;
    	
		@Override
		protected Void doInBackground(Void... params) {
			mItems = ValtoServices.getFriendsListCheckedInEvent(mEvent.getId());
			return null;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mEventFriendsList.setText(R.string.loading_friends_checkin);
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			
			if (mItems == null){
				mEventFriendsList.setText(R.string.friends_list_error);
				return;
			}
			
    		mEventFriendsList.setText(GetFriendsListText(mItems));
		}
    }
}
